package com.probox.common.entity.service.customer.impl;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.probox.common.core.enums.DataStatus;
import com.probox.common.core.exception.BaseException;
import com.probox.common.core.utils.SecurityUtils;
import com.probox.common.core.utils.StringUtils;
import com.probox.common.entity.domain.customer.CustomerGroupDefinition;
import com.probox.common.entity.domain.customer.LevelPrivilege;
import com.probox.common.entity.mapper.customer.CustomerGroupDefinitionMapper;
import com.probox.common.entity.mapper.customer.LevelPrivilegeMapper;
import com.probox.common.entity.service.customer.ILevelPrivilegeService;
import com.probox.common.entity.vo.customer.LevelPrivilegeVo;
import com.probox.customer.api.domain.CreateInfoVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.Arrays;
import java.util.List;

/**
 * 自定义权益Service业务层处理
 *
 * @author zhusiyu
 * @date 2021-05-27
 */
@Service
@Transactional
public class LevelPrivilegeServiceImpl extends ServiceImpl<LevelPrivilegeMapper, LevelPrivilege> implements ILevelPrivilegeService {
    @Autowired
    private LevelPrivilegeMapper levelPrivilegeMapper;

    @Autowired
    private CustomerGroupDefinitionMapper customerGroupDefinitionMapper;


    /**
     * @return
     */
    @Override
    public LevelPrivilege selectByName(String value) {
        QueryWrapper<LevelPrivilege> queryWrapper = Wrappers.query();
        queryWrapper.eq("PRIVILEGE_NAME", value);
        queryWrapper.eq("status", DataStatus.valid.getKey());
        queryWrapper.eq("PRIVILEGE_STATUS", DataStatus.valid.getKey());
        return levelPrivilegeMapper.selectOne(queryWrapper);
    }

    /**
     * 查询自定义权益
     *
     * @param privilegeUid 自定义权益ID
     * @return 自定义权益
     */
    @Override
    public LevelPrivilege selectLevelPrivilegeById(Long privilegeUid) {
        return this.getById(privilegeUid);
    }

    /**
     * 查询自定义权益列表
     *
     * @param levelPrivilege 自定义权益
     * @return 自定义权益
     */
    @Override
    public List<LevelPrivilege> queryList(LevelPrivilege levelPrivilege) {
        QueryWrapper<LevelPrivilege> queryWrapper = Wrappers.query();
        if (StringUtils.isNotEmpty(String.valueOf(levelPrivilege.getPrivilegeShowname())) && levelPrivilege.getPrivilegeShowname() != null) {
            queryWrapper.like("PRIVILEGE_SHOWNAME", levelPrivilege.getPrivilegeShowname());
        }
        if (StringUtils.isNotEmpty(String.valueOf(levelPrivilege.getPrivilegeStatus())) && levelPrivilege.getPrivilegeStatus() != null) {
            queryWrapper.eq("PRIVILEGE_STATUS", levelPrivilege.getPrivilegeStatus());
        }
        if (StringUtils.isNotEmpty(String.valueOf(levelPrivilege.getStatus())) && levelPrivilege.getStatus() != null) {
            queryWrapper.eq("STATUS", levelPrivilege.getStatus());
        }
        //queryWrapper.eq("PLATFORM_ID", SecurityUtils.getPlatformId());
        queryWrapper.ne("STATUS", "-1");
        List<LevelPrivilege> levelPrivileges = levelPrivilegeMapper.selectList(queryWrapper);
        return levelPrivileges;
    }

    /**
     * 新增自定义权益
     *
     * @param levelPrivilege 自定义权益
     * @return 结果
     */
    @Override
    public boolean insertLevelPrivilege(LevelPrivilege levelPrivilege) {
        if (ObjectUtil.isNotEmpty(levelPrivilege.getPrivilegeName())) {
            if (queryName(levelPrivilege.getPrivilegeName(), null) > 0) {
                throw new BaseException("权益名称已存在,不能重复");
            }
        }
        levelPrivilege.setPlatformId(SecurityUtils.getPlatformId());
        levelPrivilege.setCreateTime(DateUtil.date());
        levelPrivilege.setCreateUser(SecurityUtils.getUserId());
        levelPrivilege.setCreateName(SecurityUtils.getUsername());
        levelPrivilege.setStatus(DataStatus.valid.getKey());
        levelPrivilege.setPrivilegeStatus("0");
        return this.save(levelPrivilege);
    }

    /**
     * 修改自定义权益
     *
     * @param levelPrivilege 自定义权益
     * @return 结果
     */
    @Override
    public boolean updateLevelPrivilege(LevelPrivilege levelPrivilege) {
        if (ObjectUtil.isNotEmpty(levelPrivilege.getPrivilegeName())) {
            if (queryName(levelPrivilege.getPrivilegeName(), levelPrivilege.getPrivilegeUid()) > 0) {
                throw new BaseException("权益名称已存在,不能重复");
            }
        }
        levelPrivilege.setUpdateTime(DateUtil.date());
        levelPrivilege.setUpdateUser(SecurityUtils.getUserId());
        levelPrivilege.setUpdateName(SecurityUtils.getUsername());
        return this.updateById(levelPrivilege);
    }


    public Integer queryName(String name, Long uid) {
        QueryWrapper<LevelPrivilege> queryWrapper = new QueryWrapper<>();
        if (ObjectUtil.isNotEmpty(uid))
            queryWrapper.ne("PRIVILEGE_UID", uid);
        queryWrapper.eq("PRIVILEGE_NAME", name);
        queryWrapper.ne("status", DataStatus.delete.getKey());
        return levelPrivilegeMapper.selectCount(queryWrapper);
    }


    /**
     * 批量删除自定义权益
     *
     * @param privilegeUids 需要删除的自定义权益ID
     * @return 结果
     */
    @Override
    public boolean deleteLevelPrivilegeByIds(Long[] privilegeUids) {
        UpdateWrapper<LevelPrivilege> updateWrapper = new UpdateWrapper<>();
        updateWrapper.in("PRIVILEGE_UID", Arrays.asList(privilegeUids));
        updateWrapper.set("STATUS", DataStatus.delete.getKey());
        return this.update(updateWrapper);
    }

    @Override
    public LevelPrivilegeVo getprivilegeLevelInfo(String privilegeName) {
        Long platformId = SecurityUtils.getPlatformId();
        LevelPrivilegeVo levelPrivilegeVo = levelPrivilegeMapper.getprivilegeLevelInfo(privilegeName, platformId);
        return levelPrivilegeVo;
    }

    @Override
    public List<LevelPrivilege> getprivilegeInfoList() {
        QueryWrapper<LevelPrivilege> queryWrapper = Wrappers.query();
        queryWrapper.eq("PLATFORM_ID", SecurityUtils.getPlatformId());
        queryWrapper.eq("STATUS", "1");
        queryWrapper.select("PRIVILEGE_UID", "PRIVILEGE_NAME", "PRIVILEGE_SHOWNAME", "IS_GIVE_TYPE", "IS_UPGRADE", "PLATFORM_UNIT", "PRIVILEGE_STATUS");
        List<LevelPrivilege> levelPrivileges = levelPrivilegeMapper.selectList(queryWrapper);
        return levelPrivileges;
    }

    @Override
    public List<LevelPrivilege> getPrivilegeList() {
        QueryWrapper<LevelPrivilege> queryWrapper = Wrappers.query();
        queryWrapper.eq("STATUS", DataStatus.valid.getKey());
        queryWrapper.eq("IS_UPGRADE", DataStatus.invalid.getKey());
        queryWrapper.orderByAsc("PRIVILEGE_UID");
        return  levelPrivilegeMapper.selectList(queryWrapper);
    }

    @Transactional(propagation = Propagation.REQUIRES_NEW)
    @Override
    public Boolean saveDefaultPrivilegeAndDefinition(CreateInfoVo createInfoVo) {
        //平台id
        Long platform = createInfoVo.getPlatform();
        //创建人id
        Long userId = createInfoVo.getUserId();
        //创建人名称
        String userName = createInfoVo.getUserName();

        //默认权益信息
        //包邮
        LevelPrivilege freeShippingPrivilege = new LevelPrivilege(platform, "freeShipping", "包邮",
                "http://resource.tkmall.tongkeer.com/shop/maokun/6c0cbd9432b24dc9b568b21fa3621486_210731151813", "下单时享受订单包邮",
                "0", "0", null, "0", DateUtil.date(), userId, "1", userName);
        levelPrivilegeMapper.insert(freeShippingPrivilege);

        //打折
        LevelPrivilege discountPrivilege = new LevelPrivilege(platform, "discount", "打折",
                "http://resource.tkmall.tongkeer.com/shop/maokun/6cab9fa39e824dc3a21ff72815ad7bb1_210821100552", "下单享受打折优惠",
                "0", "0", "折", "0", DateUtil.date(), userId, "1", userName);
        levelPrivilegeMapper.insert(discountPrivilege);

        //送积分
        LevelPrivilege pointsPrivilege = new LevelPrivilege(platform, "points", "送积分",
                "http://resource.tkmall.tongkeer.com/shop/maokun/ba735248dbcd40988e668befefc1d5b4_210821100542", " 赠送积分",
                "1", "0", "分", "0", DateUtil.date(), userId, "1", userName);
        levelPrivilegeMapper.insert(pointsPrivilege);

        //送优惠券
        LevelPrivilege couponPrivilege = new LevelPrivilege(platform, "coupon", "送优惠券",
                "http://resource.tkmall.tongkeer.com/shop/maokun/8c6ab8883bde4ba8b27c0e168bdbf0d0_210821100533", " 赠送优惠券",
                "1", "1", null, "0", DateUtil.date(), userId, "1", userName);
        levelPrivilegeMapper.insert(couponPrivilege);

        //送赠品
        LevelPrivilege giftPrivilege = new LevelPrivilege(platform, "gift", "送赠品",
                "http://resource.tkmall.tongkeer.com/shop/maokun/b8745d8b8d874bd092ceb4f1b2e26282_210821100521", " 赠送赠品",
                "1", "1", null, "0", DateUtil.date(), userId, "1", userName);
        levelPrivilegeMapper.insert(giftPrivilege);

        //好友体验卡
//        LevelPrivilege cardPrivilege = new LevelPrivilege(platform,"card","好友体验卡",
//                null," 赠送好友体验卡",
//                "0","0",null,"0",DateUtil.date(),userId,"1",userName);
//        levelPrivilegeMapper.insert(cardPrivilege);

        //积分倍率
        LevelPrivilege multiplePointsPrivilege = new LevelPrivilege(platform, "multiplePoints", "积分倍率",
                "http://resource.tkmall.tongkeer.com/shop/maokun/06c507c8c3704e96a14fb2e396685f60_210821100510", " 赠送多倍积分，积分翻倍",
                "0", "0", "倍", "0", DateUtil.date(), userId, "1", userName);
        levelPrivilegeMapper.insert(multiplePointsPrivilege);

        //默认特征信息
        CustomerGroupDefinition shopHaveBuyDefinition = new CustomerGroupDefinition(platform, "shopHaveBuy", "店铺有购买", "选定时间内，购买过本店商品的客户(以支付成功为准，不剔除退款)", "天", "0", DateUtil.date(), userId, "1", userName);
        customerGroupDefinitionMapper.insert(shopHaveBuyDefinition);
        CustomerGroupDefinition shopNotBuyDefinition = new CustomerGroupDefinition(platform, "shopNotBuy", "店铺无购买", "选定时间内，没有购买过本店商品的客户(以支付成功为准，不剔除退款)", "天", "0", DateUtil.date(), userId, "1", userName);
        customerGroupDefinitionMapper.insert(shopNotBuyDefinition);
        CustomerGroupDefinition shopHaveAddBuyDefinition = new CustomerGroupDefinition(platform, "shopHaveAddBuy", "店铺有加购", "选定时间内，加购过本店商品的客户", "天", "0", DateUtil.date(), userId, "1", userName);
        customerGroupDefinitionMapper.insert(shopHaveAddBuyDefinition);
        CustomerGroupDefinition shopNotAddBuyDefinition = new CustomerGroupDefinition(platform, "shopNotAddBuy", "店铺无加购", "选定时间内，没有加购过本店商品的客户", "天", "0", DateUtil.date(), userId, "1", userName);
        customerGroupDefinitionMapper.insert(shopNotAddBuyDefinition);
        CustomerGroupDefinition validBugNumberDefinition = new CustomerGroupDefinition(platform, "validBugNumber", "有效购买次数", "客户累计在店内支付成功的订单数量，剔除全部退款的订单", "次", "1", DateUtil.date(), userId, "1", userName);
        customerGroupDefinitionMapper.insert(validBugNumberDefinition);
        CustomerGroupDefinition customerGroupDefinition = new CustomerGroupDefinition(platform, "validBuyMoney", "有效购买金额", "客户累计在店内支付成功的订单金额，剔除退款金额", "元", "1", DateUtil.date(), userId, "1", userName);
        customerGroupDefinitionMapper.insert(customerGroupDefinition);
        CustomerGroupDefinition validBuyMoneyDefinition = new CustomerGroupDefinition(platform, "shopHavePlaceOrder", "店铺有下单", "选定时间内，在店铺有下单行为的客户", "天", "0", DateUtil.date(), userId, "1", userName);
        customerGroupDefinitionMapper.insert(validBuyMoneyDefinition);
        CustomerGroupDefinition shopHavePlaceOrderDefinition = new CustomerGroupDefinition(platform, "shopNotPlaceOrder", "店铺无下单", "选定时间内，在店铺无下单行为的客户", "天", "0", DateUtil.date(), userId, "1", userName);
        customerGroupDefinitionMapper.insert(shopHavePlaceOrderDefinition);
        CustomerGroupDefinition notRefundOrderNumberDefinition = new CustomerGroupDefinition(platform, "notRefundOrderNumber", "无退款订单数", "客户累计在店内支付成功的订单数量，剔除全部退款的订单", "个", "1", DateUtil.date(), userId, "1", userName);
        customerGroupDefinitionMapper.insert(notRefundOrderNumberDefinition);
        CustomerGroupDefinition memberLevelDefinition = new CustomerGroupDefinition(platform, "memberLevel", "会员等级", "用户当前的会员等级", null, "2", DateUtil.date(), userId, "1", userName);
        customerGroupDefinitionMapper.insert(memberLevelDefinition);
        CustomerGroupDefinition sexDefinition = new CustomerGroupDefinition(platform, "sex", "性别", "客户的性别", null, "4", DateUtil.date(), userId, "1", userName);
        customerGroupDefinitionMapper.insert(sexDefinition);
        CustomerGroupDefinition integralDefinition = new CustomerGroupDefinition(platform, "integral", "积分", "用户当前可用积分数量", "分", "1", DateUtil.date(), userId, "1", userName);
        customerGroupDefinitionMapper.insert(integralDefinition);
        return true;
    }


}
